package com.charon.common.security.session;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.SerializationUtils;

import com.charon.common.util.JedisUtils;
/**
 * @Description: 自定义SessionDao，对Session进行增删改查的操作   
 * @author:charon [248135724@qq.com]
 * @date:   2018年12月19日 下午10:37:41     
 * @verdion V1.0
 */
public class RedisSessionDao extends AbstractSessionDAO{

	@Autowired
	private JedisUtils jedis;

	private final String SHIRO_SESSION_PREFIX="charon-shiro:";
	
	private byte[] getKey(String key){
		return (SHIRO_SESSION_PREFIX+key).getBytes();
	}
	
	private void saveSession(Session session){
		if(session!=null&&session.getId()!=null){
			byte[] key = getKey(session.getId().toString());
			System.out.println("序列化："+session.getId()+"===="+key.toString());
			byte[] value=SerializationUtils.serialize(session);
			jedis.set(key,value);
			jedis.expire(key,600);
		}
	}
	
	@Override
	public void update(Session session) throws UnknownSessionException {
		System.out.println("update:更新："+session.getId());
		saveSession(session);		
	}

	@Override
	public void delete(Session session) {
		System.out.println("delete:删除："+session.getId());
		if(session!=null&&session.getId()!=null){
			byte[] key=getKey(session.getId().toString());
			jedis.del(key);
		}
	}

	@Override
	public Collection<Session> getActiveSessions() {
		System.out.println("getActiveSessions");
		Set<byte[]> keys=jedis.keys(SHIRO_SESSION_PREFIX);
		Set<Session> sessions=new HashSet<Session>();
		if(CollectionUtils.isEmpty(sessions)){
			return sessions;
		}
		for(byte[] key : keys){
			Session session=(Session) SerializationUtils.deserialize(jedis.getValue(key));
			sessions.add(session);
		}
		return sessions;
	}

	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionId = generateSessionId(session);
		System.out.println("doCreate：创建："+session.getId());
		assignSessionId(session, sessionId);
		saveSession(session);
		return sessionId;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		System.out.println("doReadSession");
		if(sessionId==null)return null;
		byte[] key=getKey(sessionId.toString());
		System.out.println("读取："+sessionId);
		byte[] value=jedis.getValue(key);
		return (Session) SerializationUtils.deserialize(value);
	}

}
